package com.hps.lock;

import com.alibaba.druid.pool.DruidDataSource;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author heps
 * @date 2019/1/21 10:04
 */
public class DbUtil {

    private static final String DRIVER_CLASS_NAME = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql:///test?useSSL=false&useUnicode=true&characterEncoding=utf8";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static DruidDataSource dataSource = new DruidDataSource();

    static {
        try {
            Class.forName(DRIVER_CLASS_NAME);
            dataSource.setDriverClassName(DRIVER_CLASS_NAME);
            dataSource.setUrl(URL);
            dataSource.setUsername(USERNAME);
            dataSource.setPassword(PASSWORD);
            dataSource.setMaxActive(10);
            dataSource.setMinIdle(10);
            dataSource.setInitialSize(5);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private DbUtil() {}

    public static Connection getConnection() {
        try {
            return dataSource.getPooledConnection().getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void returnConnection(Connection connection) {
        dataSource.discardConnection(connection);
    }
}
